package LC;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/
 * Follow up for "Remove Duplicates":
 * What if duplicates are allowed at most twice?
 * For example,
 * Given sorted array nums = [1,1,1,2,2,3],
 * Your function should return length = 5,
 * with the first five elements of nums being 1, 1, 2, 2 and 3.
 * It doesn't matter what you leave beyond the new length.
 */
public class LC_080_RemoveDuplicatesfromSortedArrayII_Loop_Array {
    public static void main(String[] args) {
        int[] a = new int[]{1, 1, 1, 2, 2, 3};
        int len = Solution.removeDuplicates(a);
        System.out.println(len);
        System.out.println(Arrays.toString(a));
    }

    static class Solution {
        static int removeDuplicates(int[] nums) {
            if (nums.length <= 2)
                return nums.length;
            int prev = 1;
            int curr = 2;

            while (curr < nums.length) {
                if (nums[curr] == nums[prev] && nums[curr] == nums[prev - 1]) {
                    curr++;
                } else {
                    prev++;
                    nums[prev] = nums[curr];
                    curr++;
                }
            }

            return prev + 1;
        }
    }
}
